package com.yesin.upload.service;

import ch.qos.logback.classic.Logger;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.yesin.geteway.exception.ExceptionEnum;
import com.yesin.geteway.exception.YsException;
import com.yesin.upload.web.UploadController;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {
    private static final Logger logger = (Logger) LoggerFactory.getLogger(UploadController.class);
    // 文件的支持类型
    private static final List<String> suffixes = Arrays.asList("image/jpeg","image/gif");

    @Autowired
    private FastFileStorageClient storageClient;

    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        // 校验文件类型
        String type = file.getContentType();
        if(!suffixes.contains(type)){
            logger.info("文件上传失败，文件类型不匹配：{}",type);
            return null;
        }
        try{
            // 校验图片内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null){
                logger.info("文件内容不合法:{}",originalFilename);
                return null;
            }
            // 保存到服务器，返回文件地址信息
            // StorageClient.uploadFile(Bytes "二进制序列", Size "文件大小", Suffix "文件后缀", Set)
            String ext = StringUtils.substringAfterLast(originalFilename,".");
            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            // 拼接图片地址
            String url = "http://image.yeshop.com/" + storePath.getFullPath();

            return url;
        }catch(Exception e){
            logger.info("服务器内部错误:{}",originalFilename);
            return null;
        }
    }
}
